<?php

namespace AppBundle\Form;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class RegisterType extends AbstractType
{
    private $_em;

    public function __construct(\Doctrine\Common\Persistence\ObjectManager $em)
    {
        $this->_em = $em;
    }
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** @var  $data User*/
        $data = $builder->getData();
        $builder
            ->add('email',EmailType::class,[
                'constraints'=>[
                    new Constraints\NotBlank()
                ],
            ])
            ->add('username',TextType::class,[
                'constraints'=>[
                    new Constraints\NotBlank()
                ],
            ])
            ->add('password',RepeatedType::class,[
                'type'=>PasswordType::class,
                'invalid_message'=>'重复密码不正确',
                'required'=>true,
                'first_options'=>['label'=>'密码'],
                'second_options'=>['label'=>'重复密码'],
                'constraints'=>[
                    new Constraints\Callback([
                        'callback'=> function($object,ExecutionContextInterface $context) use($data){
                            $user = $this->_em->getRepository('AppBundle:User')->findOneBy([
                                'username'=>$data->getUsername(),
                            ]);
                            if($user){
                                $context->addViolation('用户名已存在');
                            }
                        }
                    ])
                ]
            ])
        ;

    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User',
        ));
    }
}
